import store from '../../store'
import * as echarts from 'echarts'

export default {
  name: 'StockCandle',
  props: {
    stockCode: String,
    stockName: String
  },
  mounted () {
    store.dispatch('stockDaily', this.stockCode)
      .then(response => {
        this.data = response.data.data.items
        this.drawLine(this.data)
      })
      .catch(error => {
        console.log('connect failed')
        console.log(error)
      })
  },
  watch: {
    stockCode (newVal, oldVal) {
      store.dispatch('stockDaily', this.stockCode)
        .then(response => {
          this.data = response.data.data.items
          this.drawLine(this.data)
        })
        .catch(error => {
          console.log('connect failed')
          console.log(error)
        })
    }
  },
  methods: {
    splitData (rawData) {
      var categoryData = []
      var values = []
      var volumes = []
      for (var i = rawData.length - 1; i >= 0; i--) {
        categoryData.push(rawData[i].splice(0, 1)[0])
        var temp = []
        temp.push(rawData[i][0])
        temp.push(rawData[i][3])
        temp.push(rawData[i][2])
        temp.push(rawData[i][1])
        values.push(temp)
        volumes.push([i, rawData[i][4], rawData[i][0] < rawData[i][1] ? 1 : -1])
      }

      return {
        categoryData: categoryData,
        values: values,
        volumes: volumes
      }
    },
    calculateMA (dayCount, data) {
      var result = []
      for (var i = 0, len = data.values.length; i < len; i++) {
        if (i < dayCount) {
          result.push('-')
          continue
        }
        var sum = 0
        for (var j = 0; j < dayCount; j++) {
          sum += data.values[i - j][1]
        }
        result.push(+(sum / dayCount).toFixed(3))
      }
      return result
    },
    drawLine (rawdata) {
      const upColor = '#ec0000'
      const upBorderColor = '#8A0000'
      const downColor = '#00da3c'
      const downBorderColor = '#008F28'
      var data = this.splitData(rawdata)
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.getInstanceByDom(document.getElementById('myChart'))
      if (myChart == null) {
        myChart = echarts.init(document.getElementById('myChart'))
      }
      myChart.clear()
      // 绘制图表
      myChart.setOption({
        title: {
          text: this.stockName,
          left: 0,
          // 设置字体样式
          textStyle: {
            fontSize: 28
          }
        },
        // 是否开启动画效果.
        animation: true,
        legend: {
          top: 9,
          left: '45%',
          data: ['日K', 'MA5', 'MA10', 'MA20', 'MA30']
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(255,255,255,0.6)',
          // 坐标轴指示器是指示坐标轴当前刻度的工具。
          axisPointer: {
            type: 'cross'
          },
          borderWidth: 1,
          borderColor: '#ccc',
          padding: 10,
          textStyle: {
            color: '#000'
          },
          position: function (pos, params, el, elRect, size) {
            var obj = { top: 10 }
            obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30
            return obj
          }
        },
        axisPointer: {
          link: { xAxisIndex: 'all' },
          label: {
            // {# 鼠标移到那里x轴和y轴显示的数字#}
            backgroundColor: '#777'
          }
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: false
            },
            brush: {
              type: ['lineX', 'clear']
            }
          }
        },
        brush: {
          xAxisIndex: 'all',
          brushLink: 'all',
          outOfBrush: {
            colorAlpha: 0.1
          }
        },
        visualMap: {
          show: false,
          seriesIndex: 5,
          dimension: 2,
          pieces: [{
            color: 'lightblue'
          }]
        },
        grid: [
          {
            left: '5%',
            right: '8%',
            height: '50%'
          },
          {
            left: '10%',
            right: '8%',
            top: '63%',
            height: '16%'
          }
        ],
        xAxis: [
          {
            type: 'category',
            // 日期,格式是['2016-03-01','2016-03-02','2016-03-03'.......]
            data: data.categoryData,
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            splitLine: { show: false },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax',
            axisPointer: {
              z: 100
            }
          },
          {
            type: 'category',
            gridIndex: 1,
            data: data.categoryData,
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false },
            splitNumber: 20,
            min: 'dataMin',
            max: 'dataMax'
          }
        ],
        yAxis: [
          {
            scale: true,
            splitArea: {
              show: true
            }
          },
          {
            scale: true,
            gridIndex: 1,
            splitNumber: 2,
            axisLabel: { show: false },
            axisLine: { show: false },
            axisTick: { show: false },
            splitLine: { show: false }
          }
        ],
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: [0, 1],
            start: 98,
            end: 100
          },
          {
            show: true,
            xAxisIndex: [0, 1],
            type: 'slider',
            top: '85%',
            start: 98,
            end: 100
          }
        ],
        series: [
          {
            name: '日K',
            type: 'candlestick',
            // 股票价格,格式是[['开盘价','收盘价','最低价',最高价,成交量],['开盘价','收盘价','最低价',最高价,成交量]....]
            data: data.values,
            itemStyle: {
              color: upColor,
              color0: downColor,
              borderColor: upBorderColor,
              borderColor0: downBorderColor
            },
            tooltip: {
              formatter: function (param) {
                param = param[0]
                return [
                  'Date: ' + param.name + '<hr size=1 style="margin: 3px 0">',
                  '开盘: ' + param.data[0] + '<br/>',
                  '收盘: ' + param.data[1] + '<br/>',
                  '最低: ' + param.data[2] + '<br/>',
                  '最高: ' + param.data[3] + '<br/>'
                ].join('')
              }
            }
          },
          {
            name: 'MA5',
            type: 'line',
            data: this.calculateMA(5, data),
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: 'MA10',
            type: 'line',
            data: this.calculateMA(10, data),
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: 'MA20',
            type: 'line',
            data: this.calculateMA(20, data),
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: 'MA30',
            type: 'line',
            data: this.calculateMA(30, data),
            smooth: true,
            lineStyle: {
              opacity: 0.5
            }
          },
          {
            name: '成交量（手）',
            type: 'bar',
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: data.volumes
          }
        ]
      })
    }
  }
}
